﻿using IOP.Extension.DependencyInjection;
using IOP.ISEA;
using IOP.SgrA;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Silk.NET.Vulkan;
using System;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;

namespace VkSample42
{
    public class WindowModule : VulkanModule, IVulkanRenderWapperModule
    {
        public VulkanRenderWapper RenderWapper { get; set; }

        protected override async Task Load(VulkanGraphicsManager manager)
        {
            try
            {
                var lDevice = manager.VulkanDevice;
                var pipeCache = lDevice.PipelineCache;
                var dispatcher = RenderWapper.GetRenderDispatcher<VulkanSwapchainRenderDispatcher>();
                var pass = dispatcher.GetSwapchainRenderPass();
                var area = RenderWapper.RenderArea;

                VulkanShaderInfo[] infos = new VulkanSPVShaderInfo[]
                {
                new VulkanSPVShaderInfo(ShaderTypes.VertexShader, "main_vert", new FileInfo(Path.Combine("shaders","vert.spv"))),
                new VulkanSPVShaderInfo(ShaderTypes.FragmentShader, "main_frag", new FileInfo(Path.Combine("shaders","frag.spv")))
                };
                manager.LoadShaders(infos);
                var command = lDevice.CreateCommandPool((device, option) =>
                {
                    option.Flags = CommandPoolCreateFlags.CommandPoolCreateResetCommandBufferBit;
                    option.QueueFamilyIndex = device.WorkQueues[0].FamilyIndex;
                }).CreatePrimaryCommandBuffer();
                var pipeline = manager.CreateEmptyPipeline($"MainPipline")
                    .BuildPipelineLayoutFromConfiguration("DescriptorSetLayoutCreateOptions", "PipelineLayoutCreateOption")
                    .BuildUniformBuffer(0, 0, sizeof(float) * 16, SharingMode.Exclusive)
                    .BuildGraphicsPipelineFromConfiguration(pass, pipeCache, infos, $"Pipeline1");
                manager.DeleteShaders(infos);

                var fence = lDevice.CreateFence();
                var group = manager.CreatePrimaryRenderGroup("MainRenderGroup", pipeline)
                .Binding(command, lDevice, pass, new Semaphore[] { dispatcher.ImageAvailableSemaphore, dispatcher.RenderFinishSemaphore }, new Fence[] { fence.RawHandle });
                group.CreateGroupRenderingAction((builder) => builder.UseMiddleware<GroupRenderingMiddleware>());
                group.CreateItemRenderingAction((builder) => builder.UseMiddleware<GroupItemMiddleware>());

                var aspect = area.Width / (float)(area.Height);
                var camera = new Camera(new Vector3(0, 0, 5), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
                camera.SetProjectMatrix(-aspect, 1.0f, 1.0f, 20.0f, ProjectMode.Orthogonal);
                group.SetCamera(camera);

                ISEADocument document = new ISEADocument();
                await document.Load(Path.Combine(AppContext.BaseDirectory, "Test42.isea"));
                var renders = await manager.CreateRenderObjectsFromISEA<RenderObject>(document);
                var archetype = ContextManager.CreateArchetype(new PositionComponent());
                ContextManager.CreateContexts(5, archetype, group, renders[0]);

                RenderWapper.CreateAndCutScene<Scene>("Main", group, typeof(TransformSystem));
            }
            catch (Exception e)
            {
                manager.Logger.LogError(e.Message);
            }
        }

        protected override Task Unload(VulkanGraphicsManager manager)
        {
            return Task.CompletedTask;
        }
    }
}
